package com.shixun.dds_11.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shixun.dds_11.context.BaseContext;
import com.shixun.dds_11.dto.JbuyDTO;
import com.shixun.dds_11.dto.OrderPageQueryDTO;
import com.shixun.dds_11.dto.OrdersInfoDTO;
import com.shixun.dds_11.entity.DdsGoods;
import com.shixun.dds_11.entity.DdsOrder;
import com.shixun.dds_11.entity.DdsOrderDetail;
import com.shixun.dds_11.entity.Orderlist;
import com.shixun.dds_11.mapper.*;
import com.shixun.dds_11.result.PageResult;
import com.shixun.dds_11.service.IDdsOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shixun.dds_11.vo.OrdersInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YSP
 * @since 2024-07-05
 */
@Service
public class DdsOrderServiceImpl extends ServiceImpl<DdsOrderMapper, DdsOrder> implements IDdsOrderService {

    @Autowired
    private DdsOrderMapper ddsOrderMapper;

    @Autowired
    private DdsOrderDetailMapper ddsOrderDetailMapper;

    @Autowired
    private DdsAddressMapper ddsAddressMapper;

    @Autowired
    private DdsGoodsMapper ddsGoodsMapper;

    @Autowired
    private OrderlistMapper orderlistMapper;

    @Override
    @Transactional
    public int insert(JbuyDTO jbuyDTO) {

        Integer userId = BaseContext.getCurrentId().intValue();
        DdsGoods ddsGoods = ddsGoodsMapper.selectById(jbuyDTO.getGoodId());
        DdsOrder ddsOrder=new DdsOrder();
        ddsOrder.setStatus("0");
        ddsOrder.setUserId(userId);
        ddsOrder.setCreateTime(LocalDateTime.now());
        ddsOrder.setNo(ddsOrder.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+userId);
        ddsOrderMapper.insert(ddsOrder);
        DdsOrderDetail ddsOrderDetail=new DdsOrderDetail();
        ddsOrderDetail.setOrderId(ddsOrder.getId());
        ddsOrderDetail.setOrderNo(ddsOrder.getNo());
        ddsOrderDetail.setGoodsName(ddsGoods.getName());
        ddsOrderDetail.setGoodsPrice(ddsGoods.getPrice());
        ddsOrderDetail.setGoodsCount(jbuyDTO.getCount());
        ddsOrderDetail.setGoodsUnit(ddsGoods.getUnit());
        ddsOrderDetail.setGoodsId(ddsGoods.getId());
        ddsOrderDetail.setSubtotal(ddsGoods.getPrice()*jbuyDTO.getCount());
        ddsOrderDetail.setPic(ddsGoods.getPic());
        ddsOrderDetailMapper.insert(ddsOrderDetail);
        return ddsOrder.getId();
    }


    /**
     * 订单列表查询(详情、分页)
     *
     * @param orderPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrderPageQueryDTO orderPageQueryDTO) {
        // 开始分页查询
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        //调用方法
        Page<DdsOrder> page = ddsOrderMapper.pageQuery(orderPageQueryDTO);

        // 加工处理
        long total = page.getTotal();
        List<DdsOrder> records = page.getResult();
        List<OrdersInfoVO> records1 = new ArrayList<>();
        for (DdsOrder order : records) {
            Integer orderId = order.getId();
            OrdersInfoDTO ordersInfoDTO = OrdersInfoDTO.builder().id(orderId).build();
            DdsOrderDetail orderDetail = ddsOrderDetailMapper.select(ordersInfoDTO);
            OrdersInfoVO ordersInfoVO = OrdersInfoVO.builder()
                    .id(orderId)
                    .detailId(orderDetail.getId())
                    .userId(orderPageQueryDTO.getUserId())
                    .goodsId(orderDetail.getGoodsId())
                    .no(order.getNo())
                    .status(order.getStatus())
                    .createTime(order.getCreateTime())
                    .goodsName(orderDetail.getGoodsName())
                    .goodsCount(orderDetail.getGoodsCount())
                    .goodsPrice(orderDetail.getGoodsPrice())
                    .goodsUnit(orderDetail.getGoodsUnit())
                    .subtotal(orderDetail.getSubtotal())
                    .build();

            records1.add(ordersInfoVO);
        }

        PageResult pageResult = new PageResult(total, records1);
        return pageResult;
    }

    /**
     * 订单详情查询
     *
     * @param ordersInfoDTO
     * @return
     */
    public List<OrdersInfoVO> select(OrdersInfoDTO ordersInfoDTO) {
        // 订单表的id
        Integer id = ordersInfoDTO.getId();
        DdsOrder ddsOrder = ddsOrderMapper.select(id);
        QueryWrapper<DdsOrderDetail> queryWrapper=new QueryWrapper<DdsOrderDetail>()
                .eq("order_id",id);
        List<DdsOrderDetail> list = ddsOrderDetailMapper.selectList(queryWrapper);


        List<OrdersInfoVO> ordersInfoVOList = new ArrayList<>();
        for (DdsOrderDetail ddsOrderDetail : list) {
            OrdersInfoVO ordersInfoVO = OrdersInfoVO.builder()
                    .id(id)
                    .detailId(ddsOrderDetail.getId())
                    .no(ddsOrder.getNo())
                    .status(ddsOrder.getStatus())
                    .goodsId(ddsOrderDetail.getGoodsId())
                    .userId(ddsOrder.getUserId())
                    .goodsName(ddsOrderDetail.getGoodsName())
                    .goodsCount(ddsOrderDetail.getGoodsCount())
                    .goodsPrice(ddsOrderDetail.getGoodsPrice())
                    .goodsUnit(ddsOrderDetail.getGoodsUnit())
                    .createTime(ddsOrder.getCreateTime()).build();
            ordersInfoVOList.add(ordersInfoVO);
        }
        return ordersInfoVOList;
    }



    /**
     * 提交订单
     *
     */
    @Override
    public void submit(Integer id) {
        DdsOrder ddsOrder = new DdsOrder();
        ddsOrder.setStatus("1");
        ddsOrder.setId(id);
        ddsOrderMapper.updateById(ddsOrder);
    }


    /**
     * 修改状态
     *
     * @param status
     * @param id
     */
    public void updateStatus(String status, Integer id) {
        DdsOrder order = new DdsOrder();
        order.setStatus(status);
        order.setId(id);
        ddsOrderMapper.update(order);
    }

    /**
     * 用于回显数据
     * @param userId
     * @return
     */
    @Override
    public DdsOrder getByUserId(Integer userId) {

        return ddsOrderMapper.getByUserId(userId);
    }

    @Override
    public PageResult detail(Integer id) {
        QueryWrapper<DdsOrderDetail> queryWrapper=new QueryWrapper<DdsOrderDetail>()
                .eq("order_id",id);
        List<DdsOrderDetail> ddsOrderDetails = ddsOrderDetailMapper.selectList(queryWrapper);
        return new PageResult(ddsOrderDetails.size(),ddsOrderDetails);
    }

    @Override
    public PageResult getList(Integer page) {
        int userId = BaseContext.getCurrentId().intValue();
        QueryWrapper<DdsOrder> queryWrapper=new QueryWrapper<DdsOrder>()
                .eq("user_id",userId)
                .orderByDesc("create_time");
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DdsOrder> orderPage=page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,2),queryWrapper);
        List<DdsOrder> records = orderPage.getRecords();
        List<List<Orderlist>> list =new ArrayList<>();

        for (DdsOrder order : records) {

            QueryWrapper<Orderlist> queryWrapper_detail=new QueryWrapper<Orderlist>()
                    .eq("order_id",order.getId());

            list.add(orderlistMapper.selectList(queryWrapper_detail));
        }
        return new PageResult(orderPage.getTotal(),list);
    }


}
